package com.whty.mongodemo.handler;

import com.whty.mongodemo.constant.ParamKey;
import com.whty.mongodemo.service.CustomFormService;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;



@Slf4j
public class CustomFormHandler extends BaseRoutingHandler {

  private final CustomFormService service = new CustomFormService("form_schema");

  public Handler<RoutingContext> queryById() {
    return ctx -> service.queryById(ctx.pathParam("id"), this.commonReplyHandler(ctx.response()));
  }

  public Handler<RoutingContext> query() {
    return ctx -> service.query(ctx.body() != null ? ctx.body().asJsonObject() : null, this.commonReplyHandler(ctx.response()));
  }

  public Handler<RoutingContext> queryByPage() {
    return ctx -> {
      JsonObject queryParams = ctx.body().asJsonObject();
      JsonObject page = new JsonObject().put(ParamKey.PAGE_NUM, 1).put(ParamKey.PAGE_SIZE, 10);
      JsonObject query = new JsonObject();
      if (null != queryParams) {
        queryParams.forEach(entry -> {
          String k = entry.getKey();
          Object v = entry.getValue();
          if (k.equals(ParamKey.PAGE_NUM)) {
            page.put(ParamKey.PAGE_NUM, v);
          } else if (k.equals(ParamKey.PAGE_SIZE)) {
            page.put(ParamKey.PAGE_SIZE, v);
          } else {
            if ("formRef".equals(k)) { //模糊查询
              query.put(k, new JsonObject().put("$regex", v));
            } else {
              query.put(k, v);
            }
          }
        });
      }
      service.queryByPage(page, query, this.commonReplyHandler(ctx.response()));
    };
  }

  public Handler<RoutingContext> queryWithChildren() {
    return ctx -> {
      JsonObject lookup = new JsonObject()
        .put("from", "form_component")
        .put("localField", "component_id")
        .put("foreignField", "_id")
        .put("as", "component_info");
      service.queryWithLookup(lookup, ctx.body().asJsonObject(), this.commonReplyHandler(ctx.response()));
    };
  }

  public Handler<RoutingContext> insert() {
    return ctx -> {
      JsonObject query = ctx.body().asJsonObject();
      service.insert(query, this.commonReplyHandler(ctx.response()));
    };
  }


  public Handler<RoutingContext> update() {
    return ctx -> {
      JsonObject bodyData = ctx.body().asJsonObject();
      String id = bodyData.getString("_id");
      bodyData.remove("_id");
      service.updateById(id, bodyData, this.commonReplyHandler(ctx.response()));
    };
  }

  public Handler<RoutingContext> remove() {
    return ctx -> service.removeById(ctx.pathParam("id"), this.commonReplyHandler(ctx.response()));
  }
}
